package com.gxa.admin.recycling.controller;

import com.github.pagehelper.PageInfo;
import com.gxa.admin.recycling.service.*;
import com.gxa.core.recycling.common.ExceptionCode;
import com.gxa.core.recycling.common.JsonResult;
import com.gxa.core.recycling.exception.BusinessException;
import com.gxa.core.recycling.pojo.Admin;
import com.gxa.core.recycling.pojo.Menu;
import com.gxa.core.recycling.pojo.Role;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author R
 * @data 2021-12-02 16:42
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "管理员管理")
@Transactional(rollbackFor = Throwable.class)
public class AdminController {

    @Autowired
    AdminService service;

    @Autowired
    MenuService menuService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    AdminRoleService adminRoleService;

    @PostMapping("/getAllAdmin")
    @ApiOperation("查询所有管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickName",value = "用户名",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "真实姓名",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "from",value = "创建时间起止时间",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "to",value = "创建时间截止时间",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page",value = "页码",required = true,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "size",value = "每页记录数",required = true,dataType = "Integer",paramType = "query")
    })
    public Map addRole(String nickName, String name,String from,String to,Integer page,Integer size){
        // 获得分页后的记录
        List<Map<String, Object>> allByPage = service.getAllByPage(nickName, name, from, to, page, size);
        // 获得总记录数
        Integer allByPageCount = service.getAllByPageCount(nickName, name, from, to, page, size);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("添加成功");
        jsonResult.setCode("200");
        jsonResult.setData(allByPage);
        jsonResult.put("count",allByPageCount);
        return jsonResult.getDataMap();
    }

    @PostMapping("/addAdmin")
    @ApiOperation("添加管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickName",value = "管理员用户名",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "真实姓名",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sex",value = "性别",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "province",value = "所在区域",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pwd",value = "密码",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "secondPwd",value = "第二次密码",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "rid",value = "对应角色id",required = true,dataType = "Integer",paramType = "query")
    })
    public Map addAdmin(String nickName,String name,String sex,String province,String pwd,String secondPwd,Integer rid) throws BusinessException {
        if (pwd != null && !pwd.equals(secondPwd)){
            throw new BusinessException(ExceptionCode.PWD_CHECK_FAILED);
        }
        if (rid == null){
            throw new BusinessException(ExceptionCode.NO_ROLE_ID);
        }
        Admin admin = new Admin();
        admin.setName(name);
        admin.setNickName(nickName);
        admin.setPwd(pwd);
        admin.setProvinces(province);
        admin.setSex(sex);
        admin.setIpAdress(request.getRemoteAddr());
        admin.setRegisterTime(new Date());
        admin.setLastTime(new Timestamp(System.currentTimeMillis()));
        try {
            service.insert(admin);
            adminRoleService.add(Integer.parseInt(admin.getId().toString()),rid);
            JsonResult jsonResult = new JsonResult();
            jsonResult.setCode("200");
            jsonResult.setMsg("添加成功");
            return jsonResult.getDataMap();
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.ADMIN_EXIST);
        }
    }

    @PostMapping("/deleteAdmin")
    @ApiOperation("删除管理员")
    @ApiImplicitParam(name = "id",value = "需要删除的管理员的id",dataType = "Integer",required = true,paramType = "query")
    public Map deleteAdmin(Integer id) throws BusinessException {
        // 查找此时还有多少个超管
        Integer roleById = service.getRoleById();
        // 找到删除的用户的角色名字
        String roleNameById = service.getRoleNameById(id);
        // 如果超管个数只剩一个了，无法删除超管
        // 排除普通管理员
        System.out.println(roleNameById);
        if (roleById != null && roleById == 1 && roleNameById.equals("超级管理员")){
            throw new BusinessException(ExceptionCode.DELETE_FAILED);
        }
        //
        Integer integer = service.deleteById(id);
        adminRoleService.deleteByAdminId(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("删除成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/updatePwd")
    @ApiOperation("修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "需要修改密码的账户id",required = true,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "oldPwd",value = "原密码",dataType = "String",required = true,paramType = "query"),
            @ApiImplicitParam(name = "newPwd",value = "新密码",dataType = "String",required = true,paramType = "query"),
            @ApiImplicitParam(name = "secondPwd",value = "第二次新密码",dataType = "String",required = true,paramType = "query")
    })
    public Map updatePwd(Integer id,String oldPwd,String newPwd,String secondPwd) throws BusinessException {
        Admin admin = service.selectById(id);
        if (oldPwd != null && !oldPwd.equals(admin.getPwd())){
            throw new BusinessException(ExceptionCode.OLDPWD_CHECK_FAILED);
        }
        if (newPwd != null && !newPwd.equals(secondPwd)){
            throw new BusinessException(ExceptionCode.PWD_CHECK_FAILED);
        }
        Admin admin1 = new Admin();
        admin1.setPwd(newPwd);
        admin1.setId(admin.getId());
        Integer integer = service.updateById(admin1);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/login")
    @ApiOperation("管理员登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickName",value = "用户名",required = true,paramType = "query",dataType = "String"),
            @ApiImplicitParam(name = "pwd",value = "密码",required = true,paramType = "query",dataType = "String")
    })
    public Map login(String nickName,String pwd) throws BusinessException {
        HttpSession session = request.getSession();
        String replace = UUID.randomUUID().toString().replace("-", "");
        String remoteAddr = request.getRemoteAddr();
//        System.out.println("控制器键："+remoteAddr);
//        System.out.println("服务器token:"+replace);
        session.setAttribute(remoteAddr,replace);
        Admin admin = service.loginByPwd(nickName, pwd);
        String lastTime = admin.getLastTime().toString();
        String lastIp = admin.getIpAdress();
        List<Menu> login = menuService.login(admin.getId());
        Admin admin1 = new Admin();
        admin1.setId(admin.getId());
        admin1.setIpAdress(remoteAddr);
        admin1.setLastTime(new Timestamp(System.currentTimeMillis()));
        service.updateById(admin1);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("登陆成功");
        jsonResult.setCode("200");
        jsonResult.setData(login);
        jsonResult.put("token",replace);
        jsonResult.put("nickName",admin.getNickName());
        jsonResult.put("id",admin.getId());
        jsonResult.put("pwd",admin.getPwd());
        jsonResult.put("lastTime",lastTime);
        jsonResult.put("lastIp",lastIp);
        return jsonResult.getDataMap();
    }

    @PostMapping("/logout")
    @ApiOperation("注销登录")
    public Map logout(){
        HttpSession session = request.getSession();
        session.removeAttribute(request.getRemoteAddr());
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("注销成功");
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
}
